<template>
  <div>
    <!-- 单天天气预报扩展 -->
    <div v-if="todayWeather" class="today-forecast">
      <div class="forecast-card">
        <div class="forecast-content">
          <div class="weather-main">
            <div class="weather-icon">
              <!-- 添加天气图标 -->
              <i :class="['qi', getWeatherIconClass(todayWeather.iconDay)]"></i>
            </div>
            <div class="weather-info">
              <div class="location-temp-container">
                <span class="city-name">{{ todayWeather.city }}</span>
                <div class="temp-range">
                  <span class="high">{{ todayWeather.tempMax }}°</span>
                  <span class="separator">/</span>
                  <span class="low">{{ todayWeather.tempMin }}°</span>
                </div>
              </div>
              <div class="weather-text">{{ todayWeather.textDay }}</div>
            </div>
          </div>
          <div class="weather-details">
            <div class="detail-row">
              <div class="detail-item">
                <div class="detail-icon">🌅</div>
                <div class="detail-content">
                  <span class="value">{{ todayWeather.sunrise }} / {{ todayWeather.sunset }}</span>
                </div>
              </div>
              <div class="detail-item">
                <div class="detail-icon">💧</div>
                <div class="detail-content">
                  <span class="value">{{ todayWeather.precip }}%</span>
                </div>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <div class="detail-icon">🌡️</div>
                <div class="detail-content">
                  <span class="value">{{ todayWeather.humidity }}%</span>
                </div>
              </div>
              <div class="detail-item">
                <div class="detail-icon">💨</div>
                <div class="detail-content">
                  <span class="value">{{ todayWeather.windScaleDay }}级</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>
  </div>
</template>

<script>
import http from '@/utils/http'

export default {
  name: "Wetter",
  data() {
    return {
      cityCode: '',
      todayWeather: null,
      loading: false,
      apiKey: '1d1637053e324c34a25aeb628e551000'
    }
  },
  methods: {
    /**
     * 获取天气图标类名
     */
    getWeatherIconClass(iconCode) {
      // 和风天气图标类名映射（正确的类名格式）
      const iconMap = {
        '100': 'qi-100', // 晴
        '101': 'qi-101', // 多云
        '102': 'qi-102', // 少云
        '103': 'qi-103', // 晴间多云
        '104': 'qi-104', // 阴
        '150': 'qi-150', // 晴（夜）
        '151': 'qi-151', // 多云（夜）
        '152': 'qi-152', // 少云（夜）
        '153': 'qi-153', // 晴间多云（夜）
        '300': 'qi-300', // 阵雨
        '301': 'qi-301', // 强阵雨
        '302': 'qi-302', // 雷阵雨
        '303': 'qi-303', // 强雷阵雨
        '304': 'qi-304', // 雷阵雨伴有冰雹
        '305': 'qi-305', // 小雨
        '306': 'qi-306', // 中雨
        '307': 'qi-307', // 大雨
        '308': 'qi-308', // 极端降雨
        '309': 'qi-309', // 毛毛雨/细雨
        '310': 'qi-310', // 暴雨
        '311': 'qi-311', // 大暴雨
        '312': 'qi-312', // 特大暴雨
        '313': 'qi-313', // 冻雨
        '314': 'qi-314', // 小到中雨
        '315': 'qi-315', // 中到大雨
        '316': 'qi-316', // 大到暴雨
        '317': 'qi-317', // 暴雨到大暴雨
        '318': 'qi-318', // 大暴雨到特大暴雨
        '350': 'qi-350', // 阵雨（夜）
        '351': 'qi-351', // 强阵雨（夜）
        '399': 'qi-399', // 雨
        '400': 'qi-400', // 小雪
        '401': 'qi-401', // 中雪
        '402': 'qi-402', // 大雪
        '403': 'qi-403', // 暴雪
        '404': 'qi-404', // 雨夹雪
        '405': 'qi-405', // 雨雪天气
        '406': 'qi-406', // 阵雨夹雪
        '407': 'qi-407', // 阵雪
        '408': 'qi-408', // 小到中雪
        '409': 'qi-409', // 中到大雪
        '410': 'qi-410', // 大到暴雪
        '456': 'qi-456', // 阵雨夹雪（夜）
        '457': 'qi-457', // 阵雪（夜）
        '499': 'qi-499', // 雪
        '500': 'qi-500', // 薄雾
        '501': 'qi-501', // 雾
        '502': 'qi-502', // 霾
        '503': 'qi-503', // 扬沙
        '504': 'qi-504', // 浮尘
        '507': 'qi-507', // 沙尘暴
        '508': 'qi-508', // 强沙尘暴
        '509': 'qi-509', // 浓雾
        '510': 'qi-510', // 强浓雾
        '511': 'qi-511', // 中度霾
        '512': 'qi-512', // 重度霾
        '513': 'qi-513', // 严重霾
        '514': 'qi-514', // 大雾
        '515': 'qi-515', // 特强浓雾
        '900': 'qi-900', // 热
        '901': 'qi-901', // 冷
        '999': 'qi-999'  // 未知
      };

      return iconMap[iconCode] || 'qi-999';
    },

    /**
     * 获取天气
     */
    getWeather() {
      this.loading = true;
      http.get("/home/getWeather", {}).then(response => {
        let res = response.data;
        if (res.status === 'error') {
          if (res.code !== 401) {
            this.$message.error(res.msg);
          }
          this.loading = false;
          return;
        }
        this.cityCode = res.data;
        this.getBreezyWeather();
        this.getTodayWeather();

      }).catch(error => {
        this.$message.error(error.message);
        this.loading = false;
      });
    },

    /**
     * 和风天气插件
     */
    getBreezyWeather() {
      window.WIDGET = {
        "CONFIG": {
          "layout": "1",
          "height": "150",
          "background": "1",
          "dataColor": "FFFFFF",
          "city": "CN" + this.cityCode,
          "key": "77f6f636d00c4ec8bc4ba844316ee3b0"
        }
      };

      this.cleanupWeatherWidget();

      (function (d) {
        let c = d.createElement('link')
        c.rel = 'stylesheet'
        c.href = 'https://widget.qweather.net/standard/static/css/he-standard.css?v=2.0'
        let s = d.createElement('script')
        s.src = 'https://widget.qweather.net/standard/static/js/he-standard-common.js?v=2.0'
        let sn = d.getElementsByTagName('script')[0]
        sn.parentNode.insertBefore(c, sn)
        sn.parentNode.insertBefore(s, sn)
        s.onload = () => {
          setTimeout(() => {
            const element = document.getElementById("he-plugin-standard");
            if (element) {
              element.style.width = "100%";
            }
          }, 100);
        }
      })(document)
    },

    /**
     * 获取今日天气详情
     */
    async getTodayWeather() {
      try {
        // 获取3天天气预报（包含今天）
        const forecastResponse = await fetch(
          `https://devapi.qweather.com/v7/weather/3d?location=${this.cityCode}&key=${this.apiKey}`
        );
        const forecastData = await forecastResponse.json();

        // 获取城市信息
        const cityResponse = await fetch(
          `https://geoapi.qweather.com/v2/city/lookup?location=${this.cityCode}&key=${this.apiKey}`
        );
        const cityData = await cityResponse.json();

        // 获取实时天气（用于补充数据）
        const nowResponse = await fetch(
          `https://devapi.qweather.com/v7/weather/now?location=${this.cityCode}&key=${this.apiKey}`
        );
        const nowData = await nowResponse.json();

        if (forecastData.code === '200' && cityData.code === '200' && nowData.code === '200') {
          const today = forecastData.daily[0];
          this.todayWeather = {
            city: cityData.location[0].name,
            tempMax: today.tempMax,
            tempMin: today.tempMin,
            textDay: today.textDay,
            iconDay: today.iconDay,
            sunrise: today.sunrise,
            sunset: today.sunset,
            precip: today.precip,
            humidity: nowData.now.humidity,
            pressure: nowData.now.pressure,
            vis: nowData.now.vis,
            uvIndex: today.uvIndex,
            windDirDay: today.windDirDay,
            windScaleDay: today.windScaleDay
          };
        }
      } catch (error) {
        console.error('获取今日天气详情失败:', error);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 清理天气插件
     */
    cleanupWeatherWidget() {
      const oldScripts = document.querySelectorAll('script[src*="qweather.net"]');
      const oldLinks = document.querySelectorAll('link[href*="qweather.net"]');

      oldScripts.forEach(script => script.remove());
      oldLinks.forEach(link => link.remove());
    }
  },
  mounted() {
    this.getWeather();
  },
  beforeDestroy() {
    this.cleanupWeatherWidget();
  }
}
</script>

<style scoped>
/* 引入和风天气图标字体 */
@import url('https://cdn.jsdelivr.net/npm/qweather-icons@1.0.0/font/qweather-icons.css');

/* 今日天气预报样式 */
.today-forecast {
  height: 150px;
  background-color: white;
}

.forecast-card {
  background: white;
  border-radius: 8px;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  height: 100%;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  color: #e2e8f0;
}

.forecast-content {
  padding: 10px 12px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.weather-main {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  flex: 1;
  min-height: 50px;
}

.weather-icon {
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border-radius: 50%;
  color: white;
  font-size: 20px;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.weather-info {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 40px;
}

.location-temp-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.city-name {
  font-size: 14px;
  font-weight: 600;
  color: #f1f5f9;
  margin-right: 8px;
  line-height: 1.2;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.temp-range {
  display: flex;
  align-items: center;
  line-height: 1.2;
}

.high {
  font-size: 16px;
  font-weight: bold;
  color: #f87171;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.separator {
  margin: 0 3px;
  color: #94a3b8;
  font-size: 12px;
}

.low {
  font-size: 14px;
  color: #60a5fa;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.weather-text {
  font-size: 12px;
  color: #cbd5e1;
  background: rgba(30, 41, 59, 0.7);
  padding: 4px 8px;
  border-radius: 10px;
  font-weight: 500;
  white-space: nowrap;
  border: 1px solid rgba(100, 116, 139, 0.3);
  backdrop-filter: blur(10px);
}

.weather-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  justify-content: center;
  min-height: 50px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  flex: 1;
  padding: 3px 6px;
  background: rgba(30, 41, 59, 0.6);
  border-radius: 6px;
  border: 1px solid rgba(100, 116, 139, 0.2);
  backdrop-filter: blur(5px);
  min-height: 20px;
}

.detail-icon {
  font-size: 12px;
  margin-right: 4px;
  opacity: 0.9;
}

.detail-content {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.value {
  font-size: 10px;
  color: #e2e8f0;
  font-weight: 600;
  white-space: nowrap;
  letter-spacing: 0.3px;
  line-height: 1.2;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  color: #666;
  font-size: 14px;
}

/* 科技感增强效果 */
.forecast-card {
  position: relative;
  overflow: hidden;
}

.forecast-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg,
  transparent,
  rgba(59, 130, 246, 0.5),
  transparent);
}

.weather-icon {
  position: relative;
  z-index: 2;
}

/* 移除悬停效果以节省空间 */
.detail-item {
  transition: none;
}

/* 确保总高度不超过150px */
.forecast-content {
  box-sizing: border-box;
}

.weather-main, .weather-details {
  box-sizing: border-box;
}
</style>
